"""admin/view.py存储后台管理页面的视图函数"""
import time
from datetime import datetime, timedelta
from flask import render_template, request, g, redirect, jsonify, current_app, session

from info import get_user_info, constants, db
from info.models import User, News, Category
from info.modules.admin import admin_blu
from info.utils.image_storage import image_storage
from info.utils.response_code import RET


@admin_blu.route('/login', methods=['POST', 'GET'])
def admin_login():
    """
    后台管理员登陆页面:
    1.get请求显示登陆界面
    2.post请求校验用户和密码,返回登陆后的界面
    """
    # 1.判断请求方式
    if request.method == 'GET':
        # 1.1 去session获取用户信息
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        if user_id and is_admin:
            return redirect('/admin/index')
        return render_template('admin/login.html')

    # 2.post请求时,获取参数:user,pwd
    name = request.form.get('username')
    pwd = request.form.get('password')
    if not all([name, pwd]):
        return render_template('admin/login.html', errmsg='参数不足')

    # 3.查询用户是否存在,密码是否正确,是否有权限
    try:
        user = User.query.filter(User.mobile == name).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg='数据库查询出错')
    if not user:
        return render_template('admin/login.html', errmsg='用户不存在')
    if not user.check_passowrd(pwd):
        return render_template('admin/login.html', errmsg='密码有误')
    if not user.is_admin:
        return render_template('admin/login.html', errmsg='权限不足')
    # 3.1 保存管理员信息到session中
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    session['user_id'] = user.id
    session['is_admin'] = True

    # 4.验证通过,重定向到后台管理主页
    return redirect('/admin/index')


@admin_blu.route('/index', methods=['POST', 'GET'])
@get_user_info
def admin_index():
    """
    后台管理主页
    """
    # 1. 判断用户登录状态
    user = g.user
    # if not user and not user.is_admin:
    #     return redirect('/admin/login')

    # 4.返回响应数据
    data = {'user': user.to_dict()}
    return render_template('admin/index.html', data=data)


@admin_blu.route('/user_count', methods=['POST', 'GET'])
def admin_user_count():
    """
    展示当前总人数，月活跃人数，日活跃人数
    """
    # 1.查询总人数
    total_count = 0
    try:
        total_count = User.query.filter(User.is_admin == False).count()
    except Exception as e:
        current_app.logger.error(e)

    # 2.查询月新增人数
    now = time.localtime()
    mon_count = 0
    try:
        mon_begin = '%d-%02d-01' % (now.tm_year, now.tm_mon)
        # datetime.strptime方法可以将日期格式的字符串转化为日期对象
        mon_begin_date = datetime.strptime(mon_begin, '%Y-%m-%d')
        mon_count = User.query.filter(User.is_admin == False, User.create_time >= mon_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 3.查询日新增人数
    day_count = 0
    try:
        day_begin = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
        # strptime方法可以将日期格式的字符串转化为日期对象
        day_begin_date = datetime.strptime(day_begin, '%Y-%m-%d')
        day_count = User.query.filter(User.is_admin == False, User.create_time > day_begin_date).count()
    except Exception as e:
        current_app.logger.error(e)

    # 4.查询图表信息:获取当天00:00:00时间d
    # datetime.now().strftime('%Y-%m-%d')将日期对象以固定格式转化为字符串
    now_time = '%d-%02d-%02d' % (now.tm_year, now.tm_mon, now.tm_mday)
    now_date = datetime.strptime(now_time, '%Y-%m-%d')
    active_date = []
    active_count = []
    # 4.1显示前30天的数据,再反转列表
    for i in range(31):
        # timedelta(days=i)可以将整数转化成对应值的日期对象
        begin_date = now_date - timedelta(days=i)
        end_date = begin_date + timedelta(days=1)
        active_date.append(begin_date.strftime('%Y-%m-%d'))  # 输出固定格式的日期字符串
        count = 0
        try:
            count = User.query.filter(User.is_admin == False, User.last_login >= begin_date,
                                      User.last_login < end_date).count()
        except Exception as e:
            current_app.logger.error(e)
        active_count.append(count)

    active_count.reverse()
    active_date.reverse()

    # 5.返回数据
    data = {"total_count": total_count,  # 总人数
            "mon_count": mon_count,  # 月新增人数
            "day_count": day_count,  # 日新增人数
            "active_date": active_date,  # 用户近一个月活跃日期
            "active_count": active_count  # 用户近一个月活跃人数
            }
    return render_template('admin/user_count.html', data=data)


@admin_blu.route('/user_list')
def admin_user_list():
    """列表分页展示所有用户"""
    # 1.获取参数
    page = request.args.get('page', 1)
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    total_page = 1
    current_page = 1

    # 2.查询数据
    user_list = []
    try:
        paginate = User.query.filter(User.is_admin == False).order_by(User.last_login.desc()).paginate(page,
                                                                                                       constants.ADMIN_USER_PAGE_MAX_COUNT,
                                                                                                       False)
        user_list = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
    users = [user.to_admin_dict() for user in user_list]

    # 3.返回数据
    data = {'users': users if users else None, 'total_page': total_page, 'current_page': current_page}
    return render_template('admin/user_list.html', data=data)


@admin_blu.route('/news_review')
def news_review():
    """
    返回待审核新闻列表
    """
    # 1.获取参数
    page = request.args.get('page', 1)
    keyword = request.args.get('keyword', '')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    total_page = 1
    current_page = 1

    # 2.查询数据
    news = []
    try:
        filters = [News.status != 0]
        if keyword:
            filters.append(News.title.contains(keyword))
        paginate = News.query.filter(*filters).paginate(page, constants.ADMIN_USER_PAGE_MAX_COUNT, False)

        news = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)
    news_list = [new.to_review_dict() for new in news]

    # 3.返回数据
    data = {'news_list': news_list, 'total_page': total_page, 'current_page': current_page}
    return render_template('admin/news_review.html', data=data)


@admin_blu.route('/news_review_detail', methods=['POST', 'GET'])
def news_review_detail():
    """审核新闻功能"""
    if request.method == 'GET':
        # 1.获取参数并判断:news_id
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_review_detail.html', errmsg='没有此条新闻纪录')

        # 2.查询数据
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not news:
            return render_template('admin/news_review_detail.html', errmsg='没有此条新闻纪录')

        # 3.返回响应数据
        data = {'news': news.to_dict()}
        return render_template('admin/news_review_detail.html', data=data)
    else:
        # 请求为post
        # 1.获取参数:news_id,action
        news_id = request.json.get('news_id')
        action = request.json.get('action')
        if not all([news_id, action]):
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
        if action not in ["accept", "reject"]:
            return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

        # 2.修改数据库数据
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not news:
            return jsonify(errno=RET.NODATA, errmsg='未查询到数据')
        # 2.1 根据不同操作设置不同数据
        if action == 'accept':
            news.status = 0
        else:
            # 拒绝通过,获取理由
            reason = request.json.get('reason')
            if not reason:
                return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
            news.reason = reason
            news.status = -1

        # 3.返回数据
        return jsonify(errno=RET.OK, errmsg='操作成功')


@admin_blu.route('/news_edit')
def news_edit():
    """新闻板式编辑展示"""
    # 1. 获取参数
    page = request.args.get('page', 1)
    keyword = request.args.get('keyword', '')
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
    total_page = 1
    current_page = 1

    # 2. 查询数据
    news = []
    filters = []
    try:
        if keyword:
            filters.append(News.title.contains(keyword))
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,
                                                                                          constants.ADMIN_NEWS_PAGE_MAX_COUNT,
                                                                                          False)
        news = paginate.items
        total_page = paginate.pages
        current_page = paginate.page
    except Exception as e:
        current_app.logger.error(e)

    news_list = [new.to_basic_dict() for new in news]

    # 3. 返回数据
    data = {"total_page": total_page, "current_page": current_page, "news_list": news_list}
    return render_template('admin/news_edit.html', data=data)


@admin_blu.route('/news_edit_detail', methods=['POST', 'GET'])
def news_edit_detail():
    """新闻板式编辑功能"""
    if request.method == 'GET':
        # 1.获取参数
        news_id = request.args.get('news_id')
        if not news_id:
            return render_template('admin/news_edit_detail.html', errmsg='未查询到此新闻')

        # 2.1 查询新闻
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not news:
            return render_template('admin/news_edit_detail.html', errmsg='未查询到此新闻')

        # 2.2 查询新闻分类数据
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        category_list = []
        for category in categories:
            temp_dict = category.to_dict()
            temp_dict['is_selected'] = False
            if category.id == news.category_id:
                temp_dict['is_selected'] = True
            category_list.append(temp_dict)

        category_list.pop(0)
        # 3. 返回数据
        data = {'news': news.to_dict(), 'categories': category_list}
        return render_template('admin/news_edit_detail.html', data=data)
    else:
        # post请求,修改新闻板式
        # 1.获取参数:news_id,title,digest,content,index_image,category_id
        news_id = request.form.get("news_id")
        title = request.form.get("title")
        digest = request.form.get("digest")
        content = request.form.get("content")
        index_image = request.files.get("index_image")
        category_id = request.form.get("category_id")
        # 1.1 判断数据是否有值
        if not all([title, digest, content, category_id]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数有误")
        # 1.2 判断新闻是否存在
        news = None
        try:
            news = News.query.get(news_id)
        except Exception as e:
            current_app.logger.error(e)
        if not news:
            return jsonify(errno=RET.NODATA, errmsg='未查询到此新闻')
        # 1.3 尝试读取并上传图片
        if index_image:
            try:
                index_image = index_image.read()
                key = image_storage(index_image)
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.PARAMERR, errmsg='图片参数错误或上传图片失败')

            news.index_image_url = constants.QINIU_DOMIN_PREFIX + key

        # 2.修改数据库信息
        news.title = title
        news.digest = digest
        news.content = content
        news.category_id = category_id

        # 3.返回数据
        return jsonify(errno=RET.OK, errmsg='编辑成功')


@admin_blu.route('/news_type')
def news_type():
    """新闻分类管理功能"""
    # 查询分类数据
    categories = Category.query.all()
    category_list = [category.to_dict() for category in categories]
    category_list.pop(0)

    # 返回数据
    data = {'categories': category_list}
    return render_template('admin/news_type.html', data=data)


@admin_blu.route('/add_category', methods=['POST'])
def add_category():
    """增加或修改分类"""
    # 1.获取参数
    category_id = request.json.get('id')
    category_name = request.json.get('name')
    if not category_name:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 1.1判断category_id是否存在
    if category_id:
        # 有id表示是修改数据
        try:
            category = Category.query.get(category_id)
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR, errmsg='数据库查询出错')
        if not category:
            return jsonify(errno=RET.NODATA, errmsg='未查询到分类信息')

        category.id = category_id
        category.name = category_name
    else:
        # 没有id表示新添加分类
        category = Category()
        category.name = category_name
        db.session.add(category)

    # 2.更新数据库数据
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")

    # 3.返回响应数据
    return jsonify(errno=RET.OK, errmsg='操作成功')
